package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.util.ApplicationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.Paths;

@Controller
public class PortraitController {

    private final ResourceLoader resourceLoader;

    @Autowired
    public PortraitController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping("/portrait/{fileName:.+}")
    @ResponseBody
    public ResponseEntity getPortrait(@PathVariable("fileName") String fileName) {
        String portraitPath = ApplicationUtil.getPortraitPath().getPath();
        try {
            return ResponseEntity
                    .ok()
                    .contentType(MediaType.IMAGE_PNG)
                    .body(resourceLoader.getResource("file:" + Paths.get(portraitPath, fileName).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}
